package com.javasm.filter;

import com.javasm.entity.AdminUser;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author WangJie
 * @version 1.0
 * @Description: 编码格式处理，以及登录访问控制
 * @date: 2020/7/14 18:10
 * @since JDK 1.8
 */
@WebFilter("/*")
public class CharsetFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 请求与响应乱码处理
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 登录访问控制
        //获取请求的uri
        String uri = request.getRequestURI();
        System.out.println(uri);
        //判断uri中是否包含登录相关资源
        if (uri.contains("/login.html") || uri.contains("/login")// 登录的servlet
                || uri.contains("/video")  // 前台视频的servlet
                || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/img/") || uri.contains("/png/")) {
            filterChain.doFilter(servletRequest, servletResponse);//放行
        } else {
            HttpSession session = request.getSession();
            AdminUser user = (AdminUser) session.getAttribute("loginAccount");
            if (user != null) {//用户已登录
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                response.sendRedirect(request.getContextPath() + "/login.html");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
